<script setup lang="ts">
import { request } from '@/api'
import {
  closeToast,
  showLoadingToast,
  showToast,
  type ActionSheetAction,
} from 'vant'
import { computed, onMounted, ref, watch } from 'vue'
import base64ToBlob from 'b64-to-blob'
// import { areaList } from '@vant/area-data'
// 4. 选择职业
const columns = [
  { text: '软件工程师', value: '1' },
  { text: '快递', value: '2' },
  { text: '医生', value: '3' },
  { text: '教师', value: '4' },
  { text: '律师', value: '5' },
  { text: '会计师', value: '6' },
  { text: '销售经理', value: '7' },
  { text: '市场营销专员', value: '8' },
  { text: '建筑师', value: '9' },
  { text: '护士', value: '10' },
  { text: '机械工程师', value: '11' },
]
//表单
const profile = ref<ProfileInfo>({} as ProfileInfo)
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  profile.value.profession = data.selectedValues[0]
  showProfessionPopup.value = false
}
// 显示的职业文本
const professionText = computed(() => {
  return columns.find(v => v.value === profile.value.profession)?.text
})
// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction, i: number) => {
  if (i === 0) {
    // 相册上传
    const data = await mk.pickerPhoto()
    onUpdateAvatar(data)
    // console.log('相册上传')
  } else if (i === 1) {
    // 拍照上传
    const data = mk.pickerCamera()
    onUpdateAvatar(data)
    // console.log('拍照上传')
  }
}
// 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = base64ToBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>(
      'member/profile/avatar',
      fd,
    )
    profile.value.avatar = URL.createObjectURL(image)
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (err) {
    showToast({ message: '上传失败' })
  }
}

const showBirthdayPopup = ref(false)
const onChangeBirthday = a => {
  profile.value.birthday = a.selectedValues.join('-')
  showBirthdayPopup.value = false
}
//#region 编辑个人资料
const editProfile = ref<IEditProfile>({} as IEditProfile)
watch(
  profile,
  () => {
    editProfile.value.nickname = profile.value.nickname
    editProfile.value.gender = profile.value.gender
    editProfile.value.birthday = profile.value.birthday
    // 省市区单独处理
    console.log(JSON.stringify(editProfile.value))
  },
  {
    deep: true,
  },
)
const onAreaConfirm = a => {
  // console.log('xxxx', JSON.stringify(a))
  // 省份 220000
  editProfile.value.provinceCode = a.selectedValues[0]
  // 城市
  editProfile.value.cityCode = a.selectedValues[1]
  // 地区
  editProfile.value.countyCode = a.selectedValues[2]

  // 选择的省份 文本
  const provinceText =
    areaColumns.value?.province_list[editProfile.value.provinceCode]
  // 城市
  const cityText = areaColumns.value?.city_list[editProfile.value.cityCode]
  // 地区
  const countyText =
    areaColumns.value?.county_list[editProfile.value.countyCode]

  // 显示到组件上
  profile.value.fullLocation = provinceText + cityText + countyText

  showLocationPopup.value = false

  /*
  areaList =  {
  province_list:{
  "110000":北京,
  "220000":吉林
  }
  city_list: {
  "110100":"北京",
  "220400":"辽源市"
  }
  county_list: Record<number, string>
}


   */
}
// 3. 选择所在地
const areaColumns = ref<AreaColumns>()
const showLocationPopup = ref(false)
onMounted(async () => {
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  closeToast()
  profile.value = res.data.result
  areaColumns.value = await mk.getAreaColumns()
})
// const onSelectedLocation = (data: { selectedValues: number[] }) => {
//   showLocationPopup.value = false
//   console.log(data)
// }
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="[{ name: '相册' }, { name: '拍照' }]"
      @select="onSelectAvatar"
      cancel-text="取消"
      :style="{ paddingBottom: '20px' }"
    ></van-action-sheet>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field
        label="昵称"
        v-model="profile.nickname"
        placeholder="请输入昵称"
      ></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        readonly
        placeholder="请选择日期"
        v-model="profile.birthday"
        @click="showBirthdayPopup = true"
      ></van-field>
      <!-- 选择生日弹层 -->
      <van-popup v-model:show="showBirthdayPopup" round position="bottom">
        <van-date-picker
          title="选择日期"
          @cancel="showBirthdayPopup = false"
          @confirm="onChangeBirthday"
          :min-date="new Date('1980-01-01')"
        />
      </van-popup>
      <van-field
        label="所在地"
        readonly
        placeholder="请选择所在地"
        v-model="profile.fullLocation"
        @click="showLocationPopup = true"
      ></van-field>
      <!-- 选择所在地弹层 -->
      <van-popup v-model:show="showLocationPopup" round position="bottom">
        <van-area :area-list="areaColumns" @confirm="onAreaConfirm"></van-area>
      </van-popup>
      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        :model-value="professionText"
        @click="showProfessionPopup = true"
      ></van-field>
      <!-- 打开选择职业弹层 -->
      <van-popup v-model:show="showProfessionPopup" round position="bottom">
        <van-picker
          :columns="columns"
          @confirm="onChangeProfession"
          @cancel="showProfessionPopup = false"
        />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary"> 保存资料 </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
/* ::v-deep(.van-cell__title) {
  background-color: red;
} */
</style>
